using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TMPro;
using UnityEngine;

namespace Utilities
{
    public class SerializeDictionary
    {
        public static string ToJson<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
        {
            return JsonUtility.ToJson(new SerializeDictionary<TKey, TValue>(dictionary));
        }

        public static Dictionary<TKey, TValue> FromJson<TKey, TValue>(string json)
        {
            return JsonUtility.FromJson<SerializeDictionary<TKey, TValue>>(json).ToDictionary();
        }
    }

    [Serializable]
    public class SerializeDictionary<TKey, TValue> : ISerializationCallbackReceiver
    {
        [SerializeField]
        private List<TKey> keys;
        [SerializeField]
        public List<TValue> values;

        private Dictionary<TKey, TValue> target;

        public SerializeDictionary(Dictionary<TKey, TValue> target)
        {
            this.target = target;
        }

        public Dictionary<TKey, TValue> ToDictionary() => target;

        public void OnBeforeSerialize()
        {
            this.keys = new List<TKey>(target.Keys);
            this.values = new List<TValue>(target.Values);
        }

        public void OnAfterDeserialize()
        {
            var count = Math.Min(this.keys.Count, this.values.Count);
            target = new Dictionary<TKey, TValue>(count);
            for (var i = 0; i < count; i++)
            {
                target.Add(keys[i], values[i]);
            }
        }
    }
}